package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.mongo.VisitorService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service
public class VisitorServiceImpl implements VisitorService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询访客id集合
     * @param userId
     * @param lastTime
     * @return
     */
    @Override
    public List<Long> findVisitorIds(Long userId, String lastTime) {
        Query query = new Query(
                Criteria.where("userId").is(userId)
                        .and("date").gt( Long.valueOf(lastTime) ) //一定要转换类型 跟mysql(自动类型提升) ,mongo不会转
        ).with(Sort.by(Sort.Order.desc("date")))
                .skip(0).limit(4);//写死查询个数 页面只需要4个
        //返回的对象
        List<Visitor> visitors = mongoTemplate.find(query, Visitor.class);

        //构建返回值
        List<Long> ids = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(visitors)){
            for (Visitor visitor : visitors) {
                ids.add(  visitor.getVisitorUserId() );//存入访客id
            }
        }
        return ids;
    }
}
